LIBRARY IEEE;
USE IEEE.STD_LOGIC_1164.ALL;
USE IEEE.STD_LOGIC_UNSIGNED.ALL;
ENTITY CNT10 IS
	PORT(
		CLKXITONG,CLKJISHUJIN,RST,EN,LOAD : IN STD_LOGIC;
		MODE : IN STD_LOGIC;				--ADD OR Subtraction
		DATA : IN STD_LOGIC_VECTOR(3 DOWNTO 0);--the data will be loaded
		DOUT : OUT STD_LOGIC_VECTOR(3 DOWNTO 0);--the data will be outputed
		JINZHI : buffer STD_LOGIC_VECTOR(3 DOWNTO 0);--set the jinzhi of computing
		COUT : OUT STD_LOGIC;--carry
		CLKFENPIN    : buffer STD_LOGIC;--the clock of division
		CLKJISHUCHU1 : buffer STD_LOGIC;--the output of DDF1
		CLKJISHUCHU2 : buffer STD_LOGIC;--the output of DDF2
		CLKJISHUCHU3 : buffer STD_LOGIC;--the output of DDF3
		CLKJISHUCHU4 : buffer STD_LOGIC;--the output of DDF4
		CLKJISHUCHU  : buffer STD_LOGIC--after releasing Shake`s output
	);
END CNT10;
ARCHITECTURE behav OF CNT10 IS
COMPONENT DFF1
	PORT(CLKDFF1,DDFF1:IN STD_LOGIC; QDFF1:OUT STD_LOGIC);
END COMPONENT;
BEGIN
PROCESS(CLKFENPIN,MODE,CLKXITONG,RST,EN,LOAD)
	VARIABLE Q     : STD_LOGIC_VECTOR(3 DOWNTO 0);
	VARIABLE COUNT : STD_LOGIC_VECTOR(9 DOWNTO 0);
BEGIN
	JINZHI <= DATA;

	--Frequency division 
	--counter division
	IF CLKXITONG'EVENT AND CLKXITONG = '1' THEN
		IF COUNT < 1000 THEN
						COUNT:=COUNT+1;
			ELSE 
				COUNT:=(OTHERS=>'0');
				CLKFENPIN <= NOT CLKFENPIN;
		END IF;
	END IF;
	--decrease Shaking
	CLKJISHUCHU <= CLKJISHUCHU1 AND CLKJISHUCHU2 AND CLKJISHUCHU3 AND CLKJISHUCHU4;
	--ADD	
	IF RST ='0' THEN Q := (OTHERS=>'0');
		ELSIF CLKJISHUCHU'EVENT AND CLKJISHUCHU = '1' THEN
			IF EN = '1' THEN
				IF(LOAD='0') THEN Q:=DATA;ELSE
					IF Q<JINZHI THEN 
							IF MODE = '1' THEN Q:=Q+1;
								ELSE 							--decrease
									Q:=Q-1;
							END IF;
					ELSE 
						IF MODE = '1' THEN Q:=(OTHERS=>'0');END IF;
					END IF;
					IF Q=JINZHI THEN IF MODE = '0' THEN Q:=Q-1; END IF;END IF;
					IF Q>JINZHI THEN Q:=JINZHI;END IF;
					
				END IF;
		END IF;
	END IF;
	-- carry or borrow
	IF Q = JINZHI THEN COUT<='1';
		ELSE COUT<='0';
	END IF;
	DOUT <= Q;
END PROCESS;
D1 : DFF1 PORT MAP(CLKDFF1=>CLKFENPIN,DDFF1=>CLKJISHUJIN,QDFF1=>CLKJISHUCHU1);
D2 : DFF1 PORT MAP(CLKDFF1=>CLKFENPIN,DDFF1=>CLKJISHUCHU1,QDFF1=>CLKJISHUCHU2);
D3 : DFF1 PORT MAP(CLKDFF1=>CLKFENPIN,DDFF1=>CLKJISHUCHU2,QDFF1=>CLKJISHUCHU3);
D4 : DFF1 PORT MAP(CLKDFF1=>CLKFENPIN,DDFF1=>CLKJISHUCHU3,QDFF1=>CLKJISHUCHU4);
END behav;